package com.simpletour.qa.service.service;

import com.simpletour.qa.common.base.BaseBiz;
import com.simpletour.qa.service.entity.BaseUser;
import com.simpletour.qa.service.entity.Question;
import com.simpletour.qa.service.repository.QuestionRepository;
import com.simpletour.qa.service.rpc.UserService;
import com.simpletour.qa.service.util.NumberUtil;
import com.simpletour.qa.service.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class QuestionService extends BaseBiz<QuestionRepository, Question, Integer> {

    public static final String DEFAULT_QUESTION_ORDER_COLUMN = "createTime";

    @Autowired
    private QuestionRepository repository;

    @Autowired
    private SolutionService solutionService;

    @Autowired
    private QuestionLikeService questionLikeService;

    @Autowired
    private UserService userService;

    @Override
    public Optional<Question> findById(Integer id) {
        Optional<Question> questionOptional = super.findById(id);
        final int currentUserId = UserUtil.currentUserId();
        return questionOptional.map(question ->
                fillQuestion(question,currentUserId)
        );
    }


    /**
     * @param page 当前页
     * @param fetch 每页的数量
     * @return 分页Question
     */
    public List<Question> findAll(Integer page, Integer fetch) {
        Page<Question> questionPage = repository.findAll(PageRequest.of(page, fetch,
                Sort.Direction.DESC, DEFAULT_QUESTION_ORDER_COLUMN));
        return fillQuestions(questionPage.getContent(),UserUtil.currentUserId());
    }

    /**
     * 保存或者更新问题，根据是否有ID
     *
     * @param question 问题
     * @return 保存后的Question
     */
    @Override
    public Question save(Question question) {
        question.setCreateTime(LocalDateTime.now());
        return super.save(question);
    }


    /**
     * 填充Question的属性
     *
     * @param questions 问题列表
     * @return 填充完User,solutionNum,questionLikeCount的问题列表
     */
    private List<Question> fillQuestions(List<Question> questions,final int currentUserId) {
        return questions.parallelStream().peek(q -> fillQuestion(q,currentUserId)).collect(Collectors.toList());
    }


    /**
     * 填充question的user,solutionNum,likeNum
     * 用于返回数据
     *
     * @param question 问题
     * @return  填充完User,solutionNum,questionLikeCount的问题
     */
    private Question fillQuestion(Question question,int currentUserId) {
        question.setSolutionNum(solutionService.findCountByQuestionId(question.getQuestionId()));
        BaseUser user = UserUtil.convertUser(userService.findUserById(question.getUserId()));
        question.setUser(user);
        question.setQuestionLikeCount(
                questionLikeService.getQuestionLikeCountInfo(currentUserId, question.getQuestionId()));
        return question;
    }

    public List<Question> search(int page,int fetch,String keyWord,String searchType) {
        //按照userId搜索
        List<Question> questions;
        if("userId".equalsIgnoreCase(searchType) && NumberUtil.isInteger(keyWord)){
            questions = repository.findByUserId(Integer.parseInt(keyWord), PageRequest.of(page,fetch,Sort.Direction.DESC,DEFAULT_QUESTION_ORDER_COLUMN));
        }
        else{
            if(!"%".equalsIgnoreCase(keyWord)){
                keyWord = "%"+keyWord+"%";
            }
            questions = repository.findByTitleLike(keyWord,PageRequest.of(page,fetch,Sort.Direction.DESC,DEFAULT_QUESTION_ORDER_COLUMN));
        }
        return fillQuestions(questions,UserUtil.currentUserId());
    }
}
